import axios from './request';
import store from '../store';
import dayjs from "dayjs"
import { Loading } from 'element-ui'
import Vue from 'vue';

/**
 * 获取请求头token
 */
function getToken(){
    let token='';
    let tokenString = localStorage.getItem("token");
    if(tokenString!==null){
        //保存登陆状态
        let tokenJson = JSON.parse(tokenString);
        //判断token是否已经过期
        let nowTimeSecond = Math.ceil((new Date()).getTime()/1000);
        if(tokenJson.timeLeft-nowTimeSecond>0){
            //过期时间+7天
            tokenJson.timeLeft = nowTimeSecond+86400*7
            token = tokenJson.token;
            localStorage.setItem("token",JSON.stringify(tokenJson));
        }
    }else{
        //未保存登陆状态
        let st=sessionStorage.getItem("token");
        token = st===null?'':st;
    }
    return token;
}

/**
 * 设置token
 * @param {string} token
 */
function setToken(token,remember){
    if(remember){
        let nowTimeSecond = Math.ceil((new Date()).getTime()/1000);
        let data = {
            timeLeft:nowTimeSecond+86400*7,
            token:token
        }
        localStorage.setItem("token",JSON.stringify(data));
    }else{
        sessionStorage.setItem("token",token);
    }
}

//请求类
function Request(){
    this.loadingInstance = null;
}
//配置处理
Request.prototype.config = function(config){
    let c = {
        headers:{"Authorization":"Bearer "+store.state.token}
    };
    if(config){
        c = Object.assign(c,config);
    }
    return c;
}
//get请求配置
Request.prototype.get = function (url,data,config){

    if(_.isObject(data) && !_.isEmpty(data)){
        if(/\?/.test(url)){
            url += "&"+ objectToQueryString(data)
        } else {
            url += "?"+objectToQueryString(data)
        }
    }

    config = this.config(config);
    return axios.get(url,config).then(response=>{
        this.loadingClose()
        return response
    })
}

//post请求配置
Request.prototype.post = function (url,data,config){
    config = this.config(config);
    return axios.post(url,data,config).then(response=>{
        this.loadingClose()
        return response
    })
}


/**
 * 关闭加载动画
 */
Request.prototype.loadingClose = function (){
    if(!_.isNull(this.loadingInstance)){
        Vue.nextTick(() => {
            this.loadingInstance.close();
            this.loadingInstance = null;
        });
    }
}



/**
 * 显示加载动画
 * @param show
 * @returns {Request}
 */
Request.prototype.loading = function(show = true){
    if(show){
        this.loadingInstance = Loading.service({background:'rgba(0, 0, 0, 0)'});
    }

    return this
}

const request = new Request();

/**
 * 验证手机号码
 * @param {*} value
 */
function checkMobile(value){
    return /^1[3456789]\d{9}$/.test(value);
}

/**
 * 对象转url参数字符串
 * @param {*} obj
 */
function objectToQueryString(obj) {
    return Object.keys(obj).map(function (key) {
      return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(obj[key]));
    }).join('&');
}

/**
 * 时间戳格式化
 */
function dateFormat(value,format="YYYY-MM-DD HH:mm:ss"){
    if(!_.isString(value) && !_.isNumber(value)){
        return ""
    }
    value +=  ""
    length = value.length
    if(length == 10){
        return dayjs.unix(value).format(format)
    } else if(length == 13){
        return dayjs.unix(value/1000).format(format)
    } else {
        return ""
    }

}

/**
 * 简单数据转换成树形数据
 */
function toTree(arr,id="id",pid="parent_id"){
    let cloneData = JSON.parse(JSON.stringify(arr))
    return  cloneData.filter(father=>{
        let branchArr = cloneData.filter(child=>father[id] == child[pid]);
        branchArr.length > 0 ? father.children = branchArr : []
        return father[pid] == 0
    });
}

export default {
    getToken,
    setToken,
    request,
    checkMobile,
    objectToQueryString,
    dateFormat,
    toTree

}
